<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>06_列表渲染_过滤与排序</title>
  </head>
  <body>
    <!--
1. 列表过滤
2. 列表排序
-->
    <div id="app">
      <input type="text" placeholder="请输入搜索名称啊" v-model="searchName" />
      <ul>
        <li v-for="person in searchPersons" :key="person.id">
          {{person.id}} : {{person.name}} : {{person.age}}
        </li>
      </ul>

      <button @click="orderType = 'asc'">年龄升序</button>
      <button @click="orderType = 'desc'">年龄降序</button>
      <button @click="orderType = 'origin'">原本顺序</button>
    </div>

    <script type="text/javascript" src="../js/vue.js"></script>
    <script type="text/javascript">
      new Vue({
        el: "#app",
        data: {
          persons: [
            { id: 1, name: "jack", age: 22 },
            { id: 2, name: "rose", age: 18 },
            { id: 3, name: "tom", age: 20 },
            { id: 4, name: "jerry", age: 16 },
            { id: 5, name: "marry", age: 28 },
            { id: 6, name: "jim", age: 19 },
            { id: 7, name: "mike", age: 21 },
          ],
          searchName: "",
          orderType: "origin",
        },
        methods: {
          setAscOrder() {
            this.orderType = "asc";
          },
          setDescOrder() {
            this.orderType = "desc";
          },
          setOriginOrder() {
            this.orderType = "origin";
          },
        },
        computed: {
          searchPersons() {
            const { searchName, persons, orderType } = this;
            const searchPersons = persons.filter((person) => {
              return person.name.includes(searchName);
            });
            if (orderType === "asc") {
              searchPersons.sort((a, b) => {
                return a.age - b.age;
              });
            }
            if (orderType === "desc") {
              searchPersons.sort((a, b) => {
                return b.age - a.age;
              });
            }
            return searchPersons;
          },
        },
      });
    </script>
  </body>
</html>
